//
//  NetworlkTools.swift
//  SynWeibo
//
//  Created by 沈艳男 on 15/9/3.
//  Copyright © 2015年 沈艳男. All rights reserved.
//

import UIKit
import AFNetworking
import ReactiveCocoa

// 请求方法
enum RequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class NetworlkTools: AFHTTPSessionManager {

    /*
    client_id ->  App key：3935689288
    App secret：1fd9cff656b4d641c9d53403eb4e89e9
    redirect_uri ->授权回调地址 www.baidu.com
    */
    
    private var client = "3935689288"
    private var secret = "1fd9cff656b4d641c9d53403eb4e89e9"
    // 这里是回调地址
    var redirectUri = "http://www.baidu.com"
    
    // 返回OAuth地址
    var authURL: NSURL {
        
        // 拼接好的URL访问资源路径
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client)&redirect_uri=\(redirectUri)"
        let url = NSURL(string: urlString)
        return url!
    }
    
    
    // 获取AccessToken
    func loadAccessToken(code: String) -> RACSignal {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": client,
                      "client_secret": secret,
                      "grant_type": "authorization_code",
                      "code": code,
                      "redirect_uri": redirectUri
        ]
        return request(.POST, URLString: urlString, parameters: params, withToken: false)
    }
    
    
    // 单例
    static let sharedTools: NetworlkTools = {
        // 制定baseURL
        var instance = NetworlkTools(baseURL: nil)
        
        // 设置反序列化支持格式
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }()
    
    
    // MARK: - 添加微博数据
    // 加载微博数据
    func loadStatUser() -> RACSignal {
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        return request(.GET, URLString: urlString, parameters: nil)
    }
    
    /// 加载用户信息
    ///
    /// - parameter uid:          	需要查询的用户ID。
    /// - parameter access_token:   OAuth授权后获得。
    ///
    /// - returns: 通过网路请求方法后去用户的信息
    func loadUserInfo(uid: String) -> RACSignal {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
//        let params = ["uid": uid, "access_token": access_token]
        let params = ["uid": uid]
        return request(RequestMethod.GET, URLString: urlString, parameters: params)
    }
    
    /// 网络请求方法
    ///
    /// - parameter method:     method
    /// - parameter URLString:  URLString
    /// - parameter parameters: 参数字典
    /// - parameter withToken:  是否包含 accessToken，默认带 token 访问
    ///
    /// - returns: RAC Signal
    private func request(method: RequestMethod, URLString: String, var parameters: [String: AnyObject]?, withToken: Bool = true) -> RACSignal {
        return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
            
            if withToken {
                // 需要增加 参数字典 中的token的参数
                // 判断token是否存在，gurad 正好和if let相反
                guard let token = UserAccountViewModel.sharedUserAccount.accessToken else {
                    // token 为 nil，此时就发送一个token为空的错误
                    subscriber.sendError(NSError(domain: "com.itheima.error", code: -1001, userInfo: ["errorMessage": "Token 为空"]))
                    return nil
                }
                
                // 判断是否传递了字典
                if parameters == nil {
                    parameters = [String: AnyObject]()
                }
                
                // 后面续传的都有值的token
                parameters!["access_token"] = token
                
            }
            
            // 1、成功回调的闭包
            let successCallBack = { (task: NSURLSessionDataTask, result: AnyObject) -> Void in
                // 将结果发送给阅读者
                subscriber.sendNext(result)
                // 完成
                subscriber.sendCompleted()
                
            }
            
            // 2、失败回调的闭包
            let failureCallBack = { (task: NSURLSessionDataTask, error: NSError) -> Void in
                print(error)
                subscriber.sendError(error)
            }
            
            // 3、根据方法，选着调用不同的网络方法
            if method == .GET {
                self.GET(URLString, parameters: parameters, success: successCallBack, failure: failureCallBack)
            }else {
                self.POST(URLString, parameters: parameters, success: successCallBack, failure: failureCallBack)
            }
            
            return nil
        })
    }

    
}
